package com.atguigu.ai.functioncall.service;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Service;

import java.util.function.Function;

@Service
@Description("数学计算服务 - 支持加减乘除、幂运算、取模等数学运算")
@JsonClassDescription("数学计算服务")
public class CalculatorService implements Function<CalculatorService.Request, CalculatorService.Response> {

    @Override
    public Response apply(Request request) {
        double result = performCalculation(request.operation(), request.a(), request.b());
        return new Response(request.operation(), request.a(), request.b(), result);
    }

    private double performCalculation(String operation, double a, double b) {
        return switch (operation.toLowerCase()) {
            case "add", "加法", "+" -> a + b;
            case "subtract", "减法", "-" -> a - b;
            case "multiply", "乘法", "*" -> a * b;
            case "divide", "除法", "/" -> {
                if (b == 0) {
                    throw new IllegalArgumentException("除数不能为零");
                }
                yield a / b;
            }
            case "power", "幂运算", "^" -> Math.pow(a, b);
            case "mod", "取模", "%" -> a % b;
            default -> throw new IllegalArgumentException("不支持的运算操作: " + operation);
        };
    }

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonClassDescription("数学计算请求参数")
    public record Request(
            @JsonProperty(required = true, value = "operation")
            @JsonPropertyDescription("运算类型：add(加法), subtract(减法), multiply(乘法), divide(除法), power(幂运算), mod(取模)")
            String operation,
            
            @JsonProperty(required = true, value = "a")
            @JsonPropertyDescription("第一个数字")
            double a,
            
            @JsonProperty(required = true, value = "b")
            @JsonPropertyDescription("第二个数字")
            double b
    ) {}

    @JsonClassDescription("数学计算响应结果")
    public record Response(String operation, double a, double b, double result) {}
}